<?php
namespace app\student\controller;

use app\common\model\Base;
use app\student\model\StudentManager;

class Login extends Base
{
    const MISS_NAME = "请输入姓名";
    const MISS_NUMBER = "请输入学号";
    const NON_EXIST = "用户不存在";

    const MISS_TOKEN = "请输入token";

    private $studentManager;

    public function __construct()
    {
        $_SERVER["HTTP_X_TOKEN"] = "none";
        parent::__construct();
        $this->studentManager = new StudentManager();
    }

    /**
     *
     * @api {post} /login 学生账号登录
     * @apiDescription 学生账号登录
     * @apiGroup student
     * @apiParam {string} name 姓名
     * @apiParam {string} number 学号
     *
     *@apiParamExample {json} Request-Example:
     *     {
     *       "name": 姓名，
     *       "number": 学号
     *     }
     *
     * @apiSuccess {String} code 0 表示失败 1 表示成功.
     * @apiSuccess {String} msg token令牌，之后的接口在http请求中在header里加上HTTP-X-TOKEN=>TOKEN.
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": "1",
     *       "msg": "token"
     *     }
     *
     */
    public function index(){
        $name = $_POST["name"];
        $number = $_POST["number"];

        if(empty($name)){
            echoJson(0, self::MISS_NAME);
        }else if(empty($number)){
            echoJson(0, self::MISS_NUMBER);
        }

        if($this->studentManager->isStudentExist($number, $name)){
            echoJson(1, $this->jwt->encode($number,$name));
        }else{
            echoJson(0,self::NON_EXIST);
        }
    }

    /**
     *
     * @api {get} /login/valid_token 验证token有效性
     * @apiDescription 验证token有效性
     * @apiGroup student
     * @apiParam {string} token token
     *
     *@apiParamExample {json} Request-Example:
     *     {
     *       "token": token，
     *     }
     *
     * @apiSuccess {String} code 0 表示失败 1 表示成功.
     * @apiSuccess {String} msg 验证token有效性,返回token中信息
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": "1",
     *       "msg": "token中信息"
     *     }
     *
     */
    public function valid_token(){
        $token = $_GET["token"];

        if(empty($token)){
            echoJson(0, self::MISS_TOKEN);
        }

        echoJson(1,$this->jwt->decode($token));
    }
}